package org.jobtask.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

public class LogIO {
	
	private BufferedWriter writer=null;
	private File tempFileName=null;
	
	public void openLogChannel(String logFile){
		this.tempFileName=new File(logFile+"#w");
		try {
			writer=new BufferedWriter(new FileWriter(this.tempFileName));
			this.logClear(this.tempFileName.getParent());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void saveLog(String line){
		try {
			this.writer.write(line);
			this.writer.newLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeLogChannel(){
		try {
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String path=this.tempFileName.getPath();
		this.tempFileName.renameTo(new File(path.substring(0,path.lastIndexOf("#w"))));
	}
	
	public File[] getLogFileList(String dir,final String prefix){
		File fdir=new File(dir);
		File[] flist=null;
		if(fdir.isDirectory()){
			flist=fdir.listFiles(new FilenameFilter(){
				@Override
				public boolean accept(File dir, String name) {
					return name.startsWith(prefix)&&name.endsWith(".log");
				}
			});
	    }
		return flist;
	}
	
	public File[] getLogFileList(String dir,String prefix,Comparator<File> compare){
		File[] flist=this.getLogFileList(dir,prefix);
		Arrays.sort(flist,compare);
		return flist;
	}
	
	public StringBuilder readLog(String logfile){
		StringBuilder buffer=new StringBuilder(512);
		try {
			BufferedReader read=new BufferedReader(new FileReader(logfile));
			String value="";
			while((value=read.readLine())!=null){
				buffer.append(value+"\n");
			}
			read.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public void logClear(String dir){
		File[] fs=this.getLogFileList(dir,"");
		Arrays.sort(fs);
		if(fs.length>300){
			for(int index=0;index<=250;index++){
				fs[index].delete();
			}
		}
	}
	
	public void logClear(){
		File[] fs=this.getLogFileList("logs","");
			for(int index=0;index<fs.length;index++){
				fs[index].delete();
			}
	}
	
    public String getLogSequence(String logName){
    	return logName.substring(0,logName.indexOf("["));
    }
    
    public String getLogDateTime(String logName){
    	StringBuilder buffer=new StringBuilder(logName.substring(logName.indexOf("[")+1,logName.lastIndexOf(")")).replace("("," "));
    	return buffer.insert(13,":").insert(16,":").toString();
    }
}
